package com.android.act;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.R;
import com.android.common.Action;
import com.android.common.JsInterface;

public class ReportWebActivity extends Activity implements
		OnMenuItemClickListener {
	private WebView mWebView;
	private ProgressBar mProgressBar;
	Button btn_back, btn_submit;
	TextView mTitle;
	Action action;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_web_view);

		action = new Action(ReportWebActivity.this);

		initViews();
		// flag = getIntent().getIntExtra("url", 0);

		loadUrl();
	}

	private void initViews() {
		mTitle = (TextView) findViewById(R.id.titlebar_name);
		mTitle.setVisibility(View.VISIBLE);
		mTitle.setText("首页");
		btn_back = (Button) findViewById(R.id.titlebar_back);
		btn_back.setVisibility(View.VISIBLE);
		btn_submit = (Button) findViewById(R.id.btn_submit);
		btn_submit.setVisibility(View.GONE);
		mWebView = (WebView) findViewById(R.id.webView1);
		mProgressBar = (ProgressBar) findViewById(R.id.titlebar_progress);
		mProgressBar.setVisibility(View.VISIBLE);
	}

	public void clickBtn(View v) {
		switch (v.getId()) {
		case R.id.titlebar_back:
			if (mWebView.canGoBack())
				mWebView.goBack();
			else {
				action.exit(ReportWebActivity.this);
			}

			break;
		case R.id.btn_submit:
			action.showShortToast("您点击了提交按钮");
			break;

		default:
			break;
		}
	}

	private void loadUrl() {
		// 设置对JS的支持
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		mWebView.loadUrl("file:///android_asset/demo.html");

		mWebView.requestFocus();// 如果不设置，则在点击网页文本输入框时，不能弹出软键盘及不响应其他的一些事件。 取消滚动条
		mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

		mWebView.setVerticalScrollBarEnabled(true);

		mWebView.getSettings()
				.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

		mWebView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d("monkey1", url);
				view.loadUrl(url);

				// CookieSyncManager.createInstance(this);
				CookieManager cookieManager = CookieManager.getInstance();
				String loginCookie = cookieManager.getCookie(url);
				// cookieManager.setCookie("name", "sfsf");
				// Toast.makeText(MainActivity.this, loginCookie, 0).show();
				// Toast.makeText(MainActivity.this, url, 0).show();

				return true;
			}

			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				Log.d("monkey2", url);
				action.startProgressDialog("正在加载");
				mProgressBar.setVisibility(View.VISIBLE);
				btn_submit.setVisibility(View.GONE);

			}

			public void onPageFinished(WebView view, String url) {
				Log.d("monkey3", url);
				action.stopProgressDialog();
				mProgressBar.setVisibility(View.GONE);
				btn_submit.setVisibility(View.VISIBLE);
			}
		});

		mWebView.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int newProgress) {
				mProgressBar.setProgress(newProgress);
			}

			public void onReceivedIcon(WebView view, Bitmap icon) {
			}

			public void onReceivedTitle(WebView view, String title) {
				mTitle.setText(title);
			}

			/**
			 * 覆盖默认的window.alert展示界面，避免title里显示为“：来自file:////”
			 */
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				final AlertDialog.Builder builder = new AlertDialog.Builder(
						view.getContext());

				builder.setTitle("提示框").setMessage(message)
						.setPositiveButton("确定", null);

				// 不需要绑定按键事件
				// 屏蔽keycode等于84之类的按键
				builder.setOnKeyListener(new OnKeyListener() {
					public boolean onKey(DialogInterface dialog, int keyCode,
							KeyEvent event) {
						Log.v("onJsAlert", "keyCode==" + keyCode + "event="
								+ event);
						return true;
					}
				});
				// 禁止响应按back键的事件
				builder.setCancelable(false);
				AlertDialog dialog = builder.create();
				dialog.show();
				result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
				return true;
				// return super.onJsAlert(view, url, message, result);
			}

			public boolean onJsBeforeUnload(WebView view, String url,
					String message, JsResult result) {
				return super.onJsBeforeUnload(view, url, message, result);
			}

			/**
			 * 覆盖默认的window.confirm展示界面，避免title里显示为“：来自file:////”
			 */
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				final AlertDialog.Builder builder = new AlertDialog.Builder(
						view.getContext());
				builder.setTitle("提示框").setMessage(message)
						.setPositiveButton("确定", new OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								result.confirm();
							}
						}).setNeutralButton("取消", new OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								result.cancel();
							}
						});
				builder.setOnCancelListener(new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						result.cancel();
					}
				});

				// 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
				builder.setOnKeyListener(new OnKeyListener() {
					@Override
					public boolean onKey(DialogInterface dialog, int keyCode,
							KeyEvent event) {
						Log.v("onJsConfirm", "keyCode==" + keyCode + "event="
								+ event);
						return true;
					}
				});
				// 禁止响应按back键的事件
				// builder.setCancelable(false);
				AlertDialog dialog = builder.create();
				dialog.show();
				return true;
				// return super.onJsConfirm(view, url, message, result);
			}

			/**
			 * 覆盖默认的window.prompt展示界面，避免title里显示为“：来自file:////”
			 * window.prompt('请输入您的域名地址', '618119.com');
			 */
			public boolean onJsPrompt(WebView view, String url, String message,
					String defaultValue, final JsPromptResult result) {
				final AlertDialog.Builder builder = new AlertDialog.Builder(
						view.getContext());

				builder.setTitle("提示框").setMessage(message);

				final EditText et = new EditText(view.getContext());
				et.setSingleLine();
				et.setText(defaultValue);
				builder.setView(et)
						.setPositiveButton("确定", new OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								result.confirm(et.getText().toString());
							}

						}).setNeutralButton("取消", new OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								result.cancel();
							}
						});

				// 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
				builder.setOnKeyListener(new OnKeyListener() {
					public boolean onKey(DialogInterface dialog, int keyCode,
							KeyEvent event) {
						Log.v("onJsPrompt", "keyCode==" + keyCode + "event="
								+ event);
						return true;
					}
				});

				// 禁止响应按back键的事件
				// builder.setCancelable(false);
				AlertDialog dialog = builder.create();
				dialog.show();
				return true;
				// return super.onJsPrompt(view, url, message, defaultValue,
				// result);
			}

		});

		mWebView.addJavascriptInterface(new JsInterface(mWebView,
				ReportWebActivity.this), "utils");
	}

	public boolean onMenuItemClick(MenuItem item) {
		switch (item.getItemId()) {
		// 向后（back）
		case 0:
			mWebView.goBack();
			break;
		// 向前（Forward）
		case 1:
			mWebView.goForward();
			break;
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem miBack = menu.add(0, 0, 0, "向后（back）");
		MenuItem miForward = menu.add(0, 1, 1, "向前（Forward）");
		miBack.setOnMenuItemClickListener(this);
		miForward.setOnMenuItemClickListener(this);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	// 设置回退
	// 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
			mWebView.goBack();
			return true;
		} else if ((keyCode == KeyEvent.KEYCODE_BACK) && !mWebView.canGoBack()) {
			action.exit(ReportWebActivity.this);

		}
		return false;
	}

	@Override
	protected void onDestroy() {
		action.stopProgressDialog();
		if (mWebView != null) {
			mWebView = null;
		}
		super.onDestroy();
	}

}
